import axios from 'axios';
import store from './../store';
import router from './../router';
import { Message } from 'element-ui';

// axios.defaults.baseURL = 'https://api.example.com';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

const _config = {
    host: 'http://119.29.83.54',
    port: '9527',
    base: '/api/v1'
};

// 由前面的config拼接而成
const Api = {
    getAuthorizersList: '/adminapi/getAuthorizersList/',        // 获取授权人员列表
    getLockCount: '/adminapi/getLockCount/',     // 获取市锁的数量
    getLockInfoById: '/adminapi/getLockInfoById/',  // 设备详情

    getLockList: '/lock/lockList',   // 锁列表
    getCardList: '/lock/cmdList',
    // getLogList: '/lock/logList',
    
    getOpenLockRecords: '/adminapi/getOpenLockRecords', // 开锁记录
    nbOpenLock: '/adminapi/nbOpenLock/',        // 发送开锁指令
    sendTempKey: '/adminapi/sendTempKey',       // 发送临时秘钥
};

const instance = axios.create({
    baseURL: _config.port ? `${_config.host}:${_config.port}${_config.base}` : _config.host,
    timeout: 10000,
    transformRequest: [],
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
        // 'content-type': 'application/x-www-form-urlencoded'
    },
    // withCredentials: true
});
// instance.defaults.baseURL  // 可以直接更改实例的默认值
instance.interceptors.request.use(function(config){
    let token = store.state.token || window._$cookie.get('wn_token');
    if( token ) config.headers.Authorization = token;
    if(config.method === 'post') {
        config.data = JSON.stringify(config.data);
    }
    // console.warn(config);
    return config;
});

instance.interceptors.response.use(response=>{
    return new Promise((resolve, reject)=>{
        let data = response.data,
            status = Number(data.status);
        if( status === 200 ) resolve(data);
        else if( status === 401 ) router.push({name: 'login'});
        else reject(data);
    });
}, error=>{ // 请求未到达服务器
    console.info(error);
    Message.error({
        showClose: true,
        message: '请求服务器失败',
        type: 'error'
    });
});


function httpGet(url, params){
    return new Promise((resolve, reject)=>{
        instance.get(url, {params}).then(resolve)
        .catch((err)=>{
            Message.error({
                showClose: true,
                message: err.msg || '获取数据错误',
                type: 'error'
            });
        });
    });
}

function httpPost(url, data = {}){
    return new Promise((resolve, reject)=>{
        instance.post(url, data).then(resolve)
        .catch((err)=>{
            Message.error({
                showClose: true,
                message: err.msg || '获取数据错误',
                type: 'error'
            });
        });
    });
}

export default {
    Api,
    instance,
    httpGet,
    httpPost
}